# coding=utf-8

import collections
import random


def random_items(lst, n = None):
    if n is None or n > len(lst) or n < 0:
        n = len(lst)
    items = [x for x in range(len(lst))]
    sel = []
    for i in range(n):
        idx = int(random.random() * (len(items) - i))
        sel.append(items[idx])
        items[idx] = items[len(items) - 1 - i]
    return [lst[x] for x in sel]


def random_item_idxs(lst, n = None):
    if n is None or n > len(lst) or n < 0:
        n = len(lst)
    items = [x for x in range(len(lst))]
    sel = []
    for i in range(n):
        idx = int(random.random() * (len(items) - i))
        sel.append(items[idx])
        items[idx] = items[len(items) - 1 - i]
    return [[x, lst[x]] for x in sel]

#n = len(ques)
#sel = []
#for i in range(n):
#    idx = int(random.random() * (len(items) - i))
#    sel.append(items[idx])
#    items[idx] = items[len(items) - 1 - i]

def generate_questions(n = 10, swap = False, option_count = 4, questions = None, groups = None):

    assert questions is not None
    assert groups is not None


    sel = random_item_idxs(questions, n)

    #print(sel)
    ques_col, ans_col = (1, 0) if swap else (0, 1)

    result = []

    for item in sel:
        r = []

        ques_idx, ques_item = item
        
        title = ques_item[ques_col]
        opt = ques_item[ans_col]
        group = ques_item[2]

        group_items = [x for x in groups[group] if x != ques_idx] # 选中同组元素
        # assert ques_idx in group_items
        # group_items.remove(ques_idx) # 删除正确答案

        if len(group_items) < 3: # 组内不够 3 个元素
            for g_idx, g in groups.items():
                if g_idx != group and len(g) > 3:
                    group_items += list(g)

        wrong_items = random_items(group_items, 3) # 选 3 个错误答案
        opt_items = random_items([ques_idx] + wrong_items)
        correct_idx = opt_items.index(ques_idx)

        r.append(title) # 添加 title
        for i in opt_items:
            r.append(questions[i][ans_col]) # 添加选项
        r.append(correct_idx)

        assert len(r) == 6

        result.append(r)


        # item = ques[item_idx]
        # r.append(item[0]) # ques
        # group = item[2] # group

    return result
